%% Functions handles ==============================

f = @(x) x^2
f(5)

% The simple one-line-of-code above is
% the same as defining the following function in a file myfun.m,
% then obtaining a handle to that function using f = @myfun.
% function res = myfun(x)
%   res=x^2
% end

%% Variable capture =============================
%  This is great for functions that have parameters!
%  Make sure you understand the variable scopes here.
a = 2;
g = @(a, x) a*x.^2
g(a, 2)
a = 3;
g(a, 2)

%% Simple optimization example =================
% see the simple code in gd.m where gd(...) is defined.
% An optimization algorithm takes several inputs,
% including a function (the cost function) and possibly
% its derivatives (here, the gradient). The cost and its
% gradient can be passed as function handles.
f = @(x) x' * x
gradf = @(x) 2 * x
[xopt, fopt, grandorm, iter] = gd(f, gradf, 0.1, [1; 1])
